import { defineStore } from "pinia"

import { loginApi, registerApi, logoutApi } from "@/api/auth"
import { getUserInfo } from "@/api/user"
import { resetRouter } from "@/router"
import { store } from "@/store"

import { LoginData, RegisterData } from "@/api/auth/types"
import { UserInfo } from "@/api/user/types"

import { useStorage } from "@vueuse/core"

export const useUserStore = defineStore("user", () => {
  const user: UserInfo = {
    roles: [],
    perms: [],
  }

  const token = useStorage("accessToken", "")

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((res) => {
          const { token: myToken } = res.data
          if (!myToken) reject("缺少token")
          token.value = `Bearer ${myToken}` // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 注册
  function register(regiterData: RegisterData) {
    return registerApi(regiterData)
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            reject("登陆过期，请重新登录")
            return
          }
          Object.assign(user, { ...data })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve) => {
      resetStore()
      location.reload() // 清空路由
      resolve()
    })
  }

  /** 清空缓存 */
  function resetStore() {
    resetRouter()
    token.value = ""
    Object.assign(user, { roles: [], perms: [] })
  }
  return {
    token,
    user,
    login,
    register,
    getInfo,
    logout,
    resetStore,
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
